// pages/user/mywallet/mywallet.js
var app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: {
      balance: 0,
      avatar: ''
    },
    takeMoney: {
      amount_sum: '',
      wechat_id: ''
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getBalance()
  },

  getBalance: function() {
    let that = this
    wx.showLoading({
      mask: true,
      title: app.globalData.loadText,
    })
    app.getAccessToken(app.getPageUrl(getCurrentPages())).then(function (accessToken) {
      wx.request({
        url: app.globalData.hostAPI + '/v1s/provider/index?access_token=' + accessToken,
        success: res => {
          if(res.data.status === 1) {
            that.setData({
              'userInfo.balance': res.data.data.balance
            })
            wx.hideLoading()
          }
        }
      })
    })
  },

  takeBalance: function() {
    let that = this,
        data = that.data
    if (data.userInfo.balance === '0.00') {
      wx.showToast({
        icon: 'none',
        title: '可提现金额为0',
      })
      return false
    }
    if (data.takeMoney.amount_sum === '') {
      wx.showToast({
        icon: 'none',
        title: '请填写提现金额',
      })
      return false
    }
    if (data.takeMoney.wechat_id === '') {
      wx.showToast({
        icon: 'none',
        title: '请填写微信号',
      })
      return false
    }

    wx.showLoading({
      mask: true,
      title: app.globalData.loadText,
    })

    app.getAccessToken(app.getPageUrl(getCurrentPages())).then(function (accessToken) {
      wx.request({
        url: app.globalData.hostAPI + '/v1s/order/withdraw?access_token=' + accessToken,
        data: {
          amount: that.data.takeMoney.amount_sum,
          account_no: that.data.takeMoney.wechat_id
        },
        success: res => {
          if(res.data.status === 1) {
            wx.hideLoading()
            wx.showModal({
              showCancel: false,
              title: '提示',
              content: '提现已经提交',
              success: res => {
                if(res.confirm) {
                  wx.switchTab({
                    url: '../user',
                  })
                }
              }
            })
          } else {
            wx.hideLoading()
            wx.showToast({
              icon: 'none',
              title: res.data.msg,
            })
          }
        }
      })
    })
  },

  /**
   * 输入框绑定
   */
  amountValue: function(e) {
    this.setData({
      'takeMoney.amount_sum': e.detail
    })
  },

  idValue: function (e) {
    this.setData({
      'takeMoney.wechat_id': e.detail
    })
  },
})